using System;
using System.Diagnostics;
using System.IO;
using Microsoft.SharePoint.Utilities;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers
{
    internal class Utilities
    {


        /// <summary>
        /// Runs the operation.
        /// </summary>
        /// <param name="args">The arguments to pass into STSADM.</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        /// <returns></returns>
        internal static int RunStsAdmOperation(string args, bool quiet)
        {
            string stsadmPath = Path.Combine(SPUtility.GetGenericSetupPath("BIN"), "stsadm.exe");

            return RunCommand(stsadmPath, args, quiet);
        }

        /// <summary>
        /// Runs the command.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="args">The args.</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        /// <returns></returns>
        internal static int RunCommand(string fileName, string args, bool quiet)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = true;
            startInfo.FileName = fileName;
            startInfo.Arguments = args;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardInput = true;
            startInfo.UseShellExecute = false;

            Process proc = new Process();
            try
            {
                proc.ErrorDataReceived += new DataReceivedEventHandler(Process_ErrorDataReceived);
                if (!quiet)
                    proc.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);

                proc.StartInfo = startInfo;
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();

                return proc.ExitCode;
            }
            finally
            {
                proc.Close();
            }
        }

        /// <summary>
        /// Handles the ErrorDataReceived event of the Process control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Diagnostics.DataReceivedEventArgs"/> instance containing the event data.</param>
        static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(e.Data);
        }

        /// <summary>
        /// Handles the OutputDataReceived event of the Process control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Diagnostics.DataReceivedEventArgs"/> instance containing the event data.</param>
        static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data == "Operation completed successfully.")
                return;

            Console.WriteLine(e.Data);
        }


        /// <summary>
        /// Gets the server relative URL from full URL.
        /// </summary>
        /// <param name="url">The STR URL.</param>
        /// <returns></returns>
        internal static string GetServerRelUrlFromFullUrl(string url)
        {
            int index = url.IndexOf("//");
            if ((index < 0) || (index == (url.Length - 2)))
            {
                throw new ArgumentException();
            }
            int startIndex = url.IndexOf('/', index + 2);
            if (startIndex < 0)
            {
                return "/";
            }
            string str = url.Substring(startIndex);
            if (str.IndexOf("?") >= 0)
                str = str.Substring(0, str.IndexOf("?"));

            if (str.IndexOf(".aspx") > 0)
                str = str.Substring(0, str.LastIndexOf("/"));

            if ((str.Length > 1) && (str[str.Length - 1] == '/'))
            {
                return str.Substring(0, str.Length - 1);
            }
            return str;
        }


    }
}
